package tt.dz.appserver.mvc.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.mortbay.log.Log;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;

import io.netty.handler.codec.http.HttpRequest;
import tt.dz.appserver.entity.model.ResultMappingEntity;
import tt.dz.appserver.entity.vo.WeiXinOrderInfoVo;
import tt.dz.appserver.service.business.FundService;
import tt.dz.appserver.util.Constants.weixinUrl;
import tt.dz.appserver.util.Result;
import tt.dz.appserver.util.WeiXinUtils;
import tt.dz.appserver.util.enums.Response;
import tt.dz.appserver.util.http.HttpUtils;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;


/**
 * 账单控制器 多例
 *
 * @author xielf
 */
@RestController
@RequestMapping("/fund")
@Scope(value = "prototype")
public class FundController {

    /**
     * 账单业务
     */
    @Resource
    private FundService fundService;
    private String secret = "3bbf9fb7d2e195548c0c08116c886aa1";
    private String appid = "wxb5e638233e616dfa";

    /**
     * 账单列表
     *
     * @param userCard
     * @param chargerId
     * @param chargerPortNo
     * @return
     */
    @RequestMapping(value = "/getFundList", produces = {"application/json;charset=utf-8"}, method = RequestMethod.GET)
    public String orderList(
            @RequestParam(value = "userId") String userId,
            @RequestParam(value = "pageNo", defaultValue = "1") String pageNo,
            @RequestParam(value = "status", required = false) String status,
            @RequestParam(value = "showHide", defaultValue = "1") String showHide
    ) {

        ResultMappingEntity resultMappingEntity = null;

        try {
            JSONObject resultJSONObject = fundService.orderList(userId, pageNo, status, showHide);
            String code = resultJSONObject.getString("code");
            String msg = resultJSONObject.getString("msg");

            if (Response.SUCCESS.getCode().equals(code)) {

                resultJSONObject.remove("code");
                resultJSONObject.remove("msg");
                resultMappingEntity = Result.responseBody(code, msg, resultJSONObject.getJSONArray("fundList"));
            } else {
                resultMappingEntity = Result.responseBody(code, msg);
            }

        } catch (Exception e) {
            e.printStackTrace();
            resultMappingEntity = Result.responseBody(Response.RUNTIME_ERROR.getCode(), Response.RUNTIME_ERROR.getMsg(), e.getMessage());
        }
        return resultMappingEntity.toString();
    }

    /**
     * @param userCard
     * @param chargerId
     * @param chargerPortNo
     * @return
     */
    @RequestMapping(value = "/getFundListOther", produces = {"application/json;charset=utf-8"}, method = RequestMethod.GET)
    public String orderListOther(
            @RequestParam(value = "userId") String userId,
            @RequestParam(value = "pageNo", defaultValue = "1") String pageNo,
            @RequestParam(value = "status", required = false) String status) {

        ResultMappingEntity resultMappingEntity = null;

        try {
            JSONObject resultJSONObject = fundService.orderListOther(userId, pageNo, status);
            String code = resultJSONObject.getString("code");
            String msg = resultJSONObject.getString("msg");

            if (Response.SUCCESS.getCode().equals(code)) {

                resultJSONObject.remove("code");
                resultJSONObject.remove("msg");
                resultMappingEntity = Result.responseBody(code, msg, resultJSONObject.getJSONArray("fundList"));
            } else {
                resultMappingEntity = Result.responseBody(code, msg);
            }

        } catch (Exception e) {
            e.printStackTrace();
            resultMappingEntity = Result.responseBody(Response.RUNTIME_ERROR.getCode(), Response.RUNTIME_ERROR.getMsg(), e.getMessage());
        }
        return resultMappingEntity.toString();
    }


    /**
     * 账单详细
     *
     * @param orderNo
     * @return
     */
    @RequestMapping(value = "/fundDetail", produces = {"application/json;charset=utf-8"}, method = RequestMethod.GET)
    public String orderList(@RequestParam(value = "orderNo") String orderNo) {

        ResultMappingEntity resultMappingEntity = null;
        try {
            JSONObject resultJSONObject = fundService.orderDetail(orderNo);
            String code = resultJSONObject.getString("code");
            String msg = resultJSONObject.getString("msg");

            if (Response.SUCCESS.getCode().equals(code)) {

                resultJSONObject.remove("code");

                resultJSONObject.remove("msg");
                resultMappingEntity = Result.responseBody(code, msg, resultJSONObject.get("orderDetail"));
            } else {
                resultMappingEntity = Result.responseBody(code, msg);
            }

        } catch (Exception e) {
            e.printStackTrace();
            resultMappingEntity = Result.responseBody(Response.RUNTIME_ERROR.getCode(), Response.RUNTIME_ERROR.getMsg(), e.getMessage());
        }
        return resultMappingEntity.toString();
    }

    /**
     * 订单结算
     *
     * @param orderNo
     * @return
     */
    @RequestMapping(value = "/balanceAccounts", produces = {"application/json;charset=utf-8"}, method = RequestMethod.PUT)
    public String balanceAccounts(String userId, @RequestParam String orderNo,
                                  @RequestParam String cardNo, @RequestParam String cardType) {

        ResultMappingEntity resultMappingEntity = null;

        try {
            JSONObject resultJSONObject = fundService.balanceAccounts(userId, orderNo, cardNo, cardType);
            String code = resultJSONObject.getString("code");
            String msg = resultJSONObject.getString("msg");

            if (Response.SUCCESS.getCode().equals(code)) {

                resultJSONObject.remove("code");
                resultJSONObject.remove("msg");
                resultMappingEntity = Result.responseBody(code, msg, resultJSONObject.get("orderDetail"));
            } else {
                resultMappingEntity = Result.responseBody(code, msg);
            }

        } catch (Exception e) {
            e.printStackTrace();
            resultMappingEntity = Result.responseBody(Response.RUNTIME_ERROR.getCode(), Response.RUNTIME_ERROR.getMsg(), e.getMessage());
        }
        return resultMappingEntity.toString();
    }

    /**
     * 获取预约折扣信息
     *
     * @param userCard
     * @param portNo
     * @param chargerId
     * @param minute
     * @param startTime
     * @return
     */
    @RequestMapping("/getReservationDiscount")
    public String getReservationDiscount(String userCard, @RequestParam(value = "plugNo") String portNo,
                                         String chargerId, String minute, String startTime) {

        ResultMappingEntity resultMappingEntity = null;

        try {
            JSONObject resultJSONObject = fundService.getReservationDiscount(userCard, portNo, chargerId, minute, startTime);
            String code = resultJSONObject.getString("code");
            String msg = resultJSONObject.getString("msg");

            if (Response.SUCCESS.getCode().equals(code)) {

                resultJSONObject.remove("code");
                resultJSONObject.remove("msg");
                resultMappingEntity = Result.responseBody(code, msg, resultJSONObject.get("orderDetail"));
            } else {
                resultMappingEntity = Result.responseBody(code, msg);
            }

        } catch (Exception e) {
            e.printStackTrace();
            resultMappingEntity = Result.responseBody(Response.RUNTIME_ERROR.getCode(), Response.RUNTIME_ERROR.getMsg(), e.getMessage());
        }
        return resultMappingEntity.toString();

    }

    /**
     * 获取用户需要支付的订单
     *
     * @param userId
     * @return
     */
    @RequestMapping(value = "/getUserNeedPayOrders", produces = {"application/json;charset=utf-8"}, method = RequestMethod.GET)
    public String getUserNeedPayOrders(@RequestParam String userId) {

        ResultMappingEntity resultMappingEntity = null;

        try {
            if (userId == null || userId.trim().equals("")) {
                new Exception();
            } else {
                resultMappingEntity = fundService.getUserNeedPayOrders(userId);
            }

        } catch (Exception e) {
            e.printStackTrace();
            resultMappingEntity = Result.responseBody(Response.RUNTIME_ERROR.getCode(), Response.RUNTIME_ERROR.getMsg(), e.getMessage());
        }
        return resultMappingEntity.toString();
    }

    @RequestMapping(value = "/generateOrders", produces = {"application/json;charset=utf-8"}, method = RequestMethod.POST)
    public String getProductOrder(@RequestParam(value = "orderNo") String orderNo,
                                  @RequestParam(value = "appId") String appId,
                                  @RequestParam(value = "body") String body,
                                  @RequestParam(value = "payType") String payType,
                                  @RequestParam(required = false,value = "openId") String openId,
                                  HttpServletRequest request) {
        ResultMappingEntity resultMappingEntity;
        try {
            String ip = getIpAddr(request);
            resultMappingEntity = fundService.getProductOrder(orderNo, appId, body, payType, openId, ip);
        } catch (Exception e) {
            e.printStackTrace();
            resultMappingEntity = Result.responseBody(Response.RUNTIME_ERROR.getCode(), Response.RUNTIME_ERROR.getMsg(), e.getMessage());
        }
        return resultMappingEntity.toString();
    }

    /**
     * 添加附加信息
     *
     * @param userId
     * @param orderNo
     * @param lables
     * @param evaluate
     * @param garde
     * @return
     */
    @RequestMapping(value = "/orderAttach", produces = {"application/json;charset=utf-8"}, method = RequestMethod.POST)
    public String orderAttach(
            @RequestParam(value = "userId") String userId,
            @RequestParam(value = "orderNo") String orderNo,
            @RequestParam(value = "lables", defaultValue = "") String lables,
            @RequestParam(value = "evaluate", defaultValue = "") String evaluate,
            @RequestParam(value = "grade", defaultValue = "") String grade) {
        ResultMappingEntity resultMappingEntity = null;
        try {
            resultMappingEntity = fundService.orderAttach(userId, orderNo, lables, evaluate, grade);
        } catch (Exception e) {
            e.printStackTrace();
            resultMappingEntity = Result.responseBody(Response.RUNTIME_ERROR.getCode(), Response.RUNTIME_ERROR.getMsg(), e.getMessage());
        }
        return resultMappingEntity.toString();
    }

    @RequestMapping(value = "/deleteOrder", produces = {"application/json;charset=utf-8"}, method = RequestMethod.DELETE)
    public String deleteOrder(@RequestParam(value = "orderNo") String orderNo, @RequestParam(value = "showHide", defaultValue = "1") String showHide) {
        ResultMappingEntity resultMappingEntity = null;
        try {
            resultMappingEntity = fundService.deleteOrder(orderNo, showHide);
        } catch (Exception e) {
            e.printStackTrace();
            resultMappingEntity = Result.responseBody(Response.RUNTIME_ERROR.getCode(), Response.RUNTIME_ERROR.getMsg(), e.getMessage());
        }
        return resultMappingEntity.toString();
    }

    @RequestMapping(value = "/scoreStation", produces = {"application/json;charset=utf-8"}, method = RequestMethod.POST)
    public String scoreStation(@RequestParam(value = "userId") String userId, @RequestParam(value = "stationId") String stationId,
                               @RequestParam(value = "score") String score) {
        ResultMappingEntity resultMappingEntity = null;
        try {
            resultMappingEntity = fundService.scoreStation(userId, stationId, score);
        } catch (Exception e) {
            e.printStackTrace();
            resultMappingEntity = Result.responseBody(Response.RUNTIME_ERROR.getCode(), Response.RUNTIME_ERROR.getMsg(), e.getMessage());
        }
        return resultMappingEntity.toString();
    }


    public static String getIpAddr(HttpServletRequest request) throws Exception {
        String ip = request.getHeader("X-Real-IP");
        if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }
        ip = request.getHeader("X-Forwarded-For");
        if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个IP值，第一个为真实IP。
            int index = ip.indexOf(',');
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        } else {
            return request.getRemoteAddr();
        }
    }

    /**
     * 查询微信订单状态
     *
     * @throws UnsupportedEncodingException
     */
    @RequestMapping(value = "/getWeixinOpenId", produces = {"application/json;charset=utf-8"}, method = RequestMethod.GET)
    public String getWeixinOpenId(@RequestParam(value = "jsCode") String jsCode) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("secret", secret);
        map.put("appid", appid);
        map.put("js_code", jsCode);
        map.put("grant_type", "authorization_code");
        String rsp = HttpUtils.getRequest("https://api.weixin.qq.com/sns/jscode2session", map);
        System.out.println(rsp);
        return rsp;

//		return rsp;
    }

    public static void main(String[] args) {
        new FundController().getUserNeedPayOrders("");
        System.out.println("09992016061500000120".length());

    }
}
